<template>
	<view class="poster-wrapper" @touchmove.stop.prevent="moveHandle" v-if="isShow">
		<view class="poster-content bg-white h-fill pad-lg v-box pos-real" @click.stop="1===1">
			<view class="flex-extend">
				<canvas class="mg-b-lg" @click.stop="" :style="{ width: canvasW + 'px', height: canvasH + 'px' }" canvas-id="my-canvas"></canvas>
			</view>
			<view v-if="extraText" class="mg-b-base h-fill">
				<view class="h-box justify-between mg-b-base">
					<text class="title">推广文案</text>
					<text @click="copy" class="text-copy">复制文案</text>
				</view>
				<scroll-view scroll-y style="max-height: 100rpx;">
					<view>{{extraText}}</view>
				</scroll-view>
			</view>
			<view class="h-box h-fill">
				<button class="flex-extend mg-r-base btn-share" open-type="share">
					<view class="btn-save h-box text-white bg-red justify-center">
						<image src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_fenxiang_anniu@2x.png" style="width: 50rpx;height: 50rpx;"></image>
						分享好友
					</view>
				</button>
				<image @click.stop="saveImage" :src="$getCloudStorageUrl('/ic_xiazai_anniu@2x.png')" style="width: 88rpx;height: 88rpx;"></image>
			</view>
			<view @click="isShow = false" class="pos-abs-rt btn-close">
				<uni-icons type="closeempty" size="30" style="line-height: 1;"></uni-icons>
			</view>
		</view>
	</view>
</template>

<script>
	export default{
		props:{
			bgImg: {
				type: String,
				default: ""
			},
			qrcodeImg: {
				type: String,
				default: ""
			},
			extraText: {
				type: String,
				default: ''
			}
		},
		data(){
			return {
				canvasW: 0,
				canvasH: 0,
				ctx: null,
				isShow: false,
			}
		},
		methods:{
			moveHandle() {
				
			},
			copy() {
				// #ifndef H5
				uni.setClipboardData({
					data: this.extraText
				})
				// #endif
			},
			//显示
			showCanvas(){
				this.isShow = true
				this.__init()
			},
			//初始化画布
			async __init(){
				uni.showLoading({
				    title: '生成海报中...',
					mask: true
				})
				let sysInfo = uni.getSystemInfoSync();
				let maxW = uni.upx2px(467);
				let maxH = uni.upx2px(700);
				let minRatio = maxW / maxH;
				
				let bgImg = await this.getImageInfo(this.bgImg)
				let ratio = bgImg.width / bgImg.height;
				if (ratio < minRatio) {
					this.canvasH = maxH;
					this.canvasW = this.canvasH * ratio;
				} else {
					this.canvasW = maxW;
					this.canvasH = this.canvasW / ratio;
				}
				// this.canvasW = sysInfo.windowWidth - 80;
				// this.canvasH = Math.round(this.canvasW / ratio);
				console.log("画布大小", `${this.canvasW},${this.canvasH}`);
				this.ctx = uni.createCanvasContext('my-canvas', this)
				//设置画布背景透明
				this.ctx.setFillStyle('rgb(255, 255, 255)')
				//设置画布大小
				this.ctx.fillRect(0, 0, this.canvasW, this.canvasH)
				//绘制圆角背景
				// this.drawRoundRect(this.ctx, 0, 0, this.canvasW, this.canvasH,uni.upx2px(18),'#FFFFFF')
				//画背景
				this.ctx.drawImage(bgImg.path, 0, 0, this.canvasW, this.canvasH);
				//画小程序码
				let qrcodeImg = await this.getImageInfo(this.qrcodeImg)
				let qrcodeSize = uni.upx2px(123) - 10;
				let qrcodeX = this.canvasW - qrcodeSize - 5;
				let qrcodeY = this.canvasH - qrcodeSize - 5;
				this.ctx.drawImage(qrcodeImg.path, qrcodeX, qrcodeY, qrcodeSize, qrcodeSize);
				//延迟渲染
				setTimeout(()=>{
					this.ctx.draw(true,()=>{
						uni.hideLoading()
					})
				},500)
			},
			//绘制实心圆
			drawEmptyRound(ctx,x,y,radius){
				ctx.save()
				ctx.beginPath();
				ctx.arc(x, y, radius, 0, 2 * Math.PI,true);
				ctx.setFillStyle('rgba(0, 0, 0, .4)')
				ctx.fill();
				ctx.restore()
				ctx.closePath()
			},
			//绘制虚线
			drawDashLine(ctx,x1,y1,x2,y2,dashLength){
				ctx.setStrokeStyle("#cccccc")//设置线条的颜色
				ctx.setLineWidth(1)//设置线条宽度
				var dashLen = dashLength,
				xpos = x2 - x1, //得到横向的宽度;
				ypos = y2 - y1, //得到纵向的高度;
				numDashes = Math.floor(Math.sqrt(xpos * xpos + ypos * ypos) / dashLen); 
				//利用正切获取斜边的长度除以虚线长度，得到要分为多少段;
				for(var i=0; i<numDashes; i++){
				 if(i % 2 === 0){
					 ctx.moveTo(x1 + (xpos/numDashes) * i, y1 + (ypos/numDashes) * i); 
					 //有了横向宽度和多少段，得出每一段是多长，起点 + 每段长度 * i = 要绘制的起点；
				  }else{
					  ctx.lineTo(x1 + (xpos/numDashes) * i, y1 + (ypos/numDashes) * i);
				  }
				}
				ctx.stroke();
			},
			//带圆角图片
			drawRoundImg(ctx, img, x, y, width, height, radius){
				ctx.beginPath()
				ctx.save()
				// 左上角
				ctx.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 1.5)
				// 右上角
				ctx.arc(x + width - radius, y + radius, radius, Math.PI * 1.5, Math.PI * 2)
				// 右下角
				ctx.arc(x + width - radius, y + height - radius, radius, 0, Math.PI * 0.5)
				// 左下角
				ctx.arc(x + radius, y + height - radius, radius, Math.PI * 0.5, Math.PI)
				ctx.stroke()
				ctx.clip()
				ctx.drawImage(img, x, y, width, height);
				ctx.restore()
				ctx.closePath()
			},
			//圆角矩形
			drawRoundRect(ctx, x, y, width, height, radius, color){
				ctx.save();
				ctx.beginPath();
				ctx.setFillStyle(color); 
				ctx.setStrokeStyle(color)
				ctx.setLineJoin('round');  //交点设置成圆角
				ctx.setLineWidth(radius);
				ctx.strokeRect(x + radius/2, y + radius/2, width - radius , height - radius );
				ctx.fillRect(x + radius, y + radius, width - radius * 2, height - radius * 2);
				ctx.stroke();
				ctx.closePath();
			},
			downloadImage(imgSrc) {
				return new Promise((resolve, reject) => {
					uni.downloadFile({
						url: imgSrc,
						success: (res) => {
							resolve(res.tempFilePath);
							console.log("图片下载成功", res);
						},
						fail: (err) => {
							reject(err);
							console.log("图片下载失败");
						}
					})
				});
			},
			//获取图片
			getImageInfo(imgSrc){
				return new Promise((resolve, reject) => {
					uni.getImageInfo({
						src: imgSrc,
						success: (image) => {
							resolve(image);
							console.log('获取图片成功',image)
						},
						fail: (err) => {
							reject(err);
							console.log('获取图片失败',err)
						}
					});
				});
			},
			//保存图片到相册
			async saveImage(){
				try{
					await new Promise((resolve, reject) => {
						uni.getSetting({
							success: (res) => {
								let t = res.authSetting["scope.writePhotosAlbum"];
								if (t !== undefined && !t) {
									// 请求过权限，但是用户关闭了
									uni.showModal({
										title: "请先打开相册开关",
										cancelText: "取消",
										confirmText: "去打开",
										success: (res) => {
											if (res.confirm) {
												uni.openSetting();
											}
										}
									})
									rejcet();
								} else {
									resolve();
								}
							}
						})
					})
				}catch(e){
					return;
				}
				var that = this
				uni.canvasToTempFilePath({
					canvasId: 'my-canvas',
					quality: 1,
					complete: (res) => {
						console.log('保存到相册',res);
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success(res) {
								uni.showToast({
									title: '已保存到相册',
									icon: 'success',
									duration: 2000
								})
								setTimeout(()=>{
									that.isShow = false
								},2000)
							}
						})
					}
				},this);
			}
		}
	}
</script>

<style scoped lang="scss">
.poster-wrapper{
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0,0,0,.4);
	display: flex;
	flex-direction: column;
	justify-content: flex-end;
	align-items: center;
	padding-top: 40px;
	z-index: 999;
	padding-bottom: constant(safe-area-inset-bottom);
	padding-bottom: env(safe-area-inset-bottom);
}
.poster-content {
	border-top-left-radius: 24rpx;
	border-top-right-radius: 24rpx;
	min-height: 600rpx;
}
.btn-save {
	height: 88rpx;
	background: #D61719;
	border-radius: 44rpx;
}
.title {
	font-size: 32rpx;
	font-family: STHeitiSC-Medium, STHeitiSC;
	font-weight: 500;
	color: #333333;
	line-height: 33rpx;
}
.text-copy {
	font-size: 26rpx;
	font-family: PingFangSC-Regular, PingFang SC;
	font-weight: 400;
	color: #D61719;
	line-height: 37rpx;
}
.btn-share {
	height: 88rpx;
	background: #D61719;
	border-radius: 44rpx;
}
.btn-share:after {
	display: none;
}
.btn-close {
	width: 30px;
	height: 30rpx;
	right: 20rpx;
	top: 20rpx;
}
// /deep/ uni-view {
// 	line-height: 1;
// }
</style>
